home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1998 November: Tool Chest / Dev.CD Nov 98 TC.toast / Sample Code / Overview / Sample / Sample.p < prev    next >
Encoding:
Text File  |  1994-11-18  |  31.9 KB  |  911 lines  |  [TEXT/MPS ]

  1. {------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple Sample Application
  6. #
  7. #    Sample
  8. #
  9. #    Sample.p    -    Pascal Source
  10. #
  11. #    Copyright © 1989 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89
  18. #                1.03                06/89
  19. #                1.04                06/92
  20. #
  21. #    Components:
  22. #                Sample.p            June 1, 1989
  23. #                Sample.c            June 1, 1989
  24. #                SampleInit.c        June 2, 1992
  25. #                Sample.a            June 1, 1989
  26. #                Sample.inc1.a        June 1, 1989
  27. #                SampleMisc.a        June 1, 1989
  28. #                Sample.r            June 1, 1989
  29. #                Sample.h            June 1, 1989
  30. #                PSample.make        June 1, 1989
  31. #                CSample.make        June 1, 1989
  32. #                ASample.make        June 1, 1989
  33. #                CSample.π            June 2, 1992
  34. #                CSample.π.rsrc        June 2, 1992
  35. #
  36. #    Sample is an example application that demonstrates how to
  37. #    initialize the commonly used toolbox managers, operate 
  38. #    successfully under MultiFinder, handle desk accessories, 
  39. #    and create, grow, and zoom windows.
  40. #
  41. #    It does not by any means demonstrate all the techniques 
  42. #    you need for a large application. In particular, Sample 
  43. #    does not cover exception handling, multiple windows/documents, 
  44. #    sophisticated memory management, printing, or undo. All of 
  45. #    these are vital parts of a normal full-sized application.
  46. #
  47. #    This application is an example of the form of a Macintosh 
  48. #    application; it is NOT a template. It is NOT intended to be 
  49. #    used as a foundation for the next world-class, best-selling, 
  50. #    600K application. A stick figure drawing of the human body may 
  51. #    be a good example of the form for a painting, but that does not 
  52. #    mean it should be used as the basis for the next Mona Lisa.
  53. #
  54. #    We recommend that you review this program or TESample before 
  55. #    beginning a new application.
  56. #
  57. ------------------------------------------------------------------------------}
  58.  
  59.  
  60. PROGRAM Sample;
  61.  
  62.  
  63. {Segmentation strategy:
  64.  
  65.  This program consists of three segments. Main contains most of the code,
  66.  including the MPW libraries, and the main program. Initialize contains
  67.  code that is only used once, during startup, and can be unloaded after the
  68.  program starts. %A5Init is automatically created by the Linker to initialize
  69.  globals for the MPW libraries and is unloaded right away.}
  70.  
  71.  
  72. {SetPort strategy:
  73.  
  74.  Toolbox routines do not change the current port. In spite of this, in this
  75.  program we use a strategy of calling SetPort whenever we want to draw or
  76.  make calls which depend on the current port. This makes us less vulnerable
  77.  to bugs in other software which might alter the current port (such as the
  78.  bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  79.  Hopefully, this also makes the routines from this program more self-contained,
  80.  since they don't depend on the current port setting.}
  81.  
  82.  
  83. USES
  84.     Types, QuickDraw, OSUtils, Files, Devices, DeskBus, DiskInit, Disks,
  85.     Errors, Memory, Retrace, SegLoad, Serial, ShutDown, Slots, Sound, Start,
  86.     Timer, Events, Controls, Windows, TextEdit,
  87.     Dialogs, Fonts, Lists,
  88.     Menus, Resources, Scrap, ToolUtils, Packages, Traps;
  89.  
  90. CONST
  91.     {1.01 - changed constants to begin with 'k' for consistency, except for resource IDs}
  92.     {SysEnvironsVersion is passed to SysEnvirons to tell it which version of the
  93.      SysEnvRec we understand.}
  94.     kSysEnvironsVersion        = 1;
  95.  
  96.     {OSEvent is the event number of the suspend/resume and mouse-moved events sent
  97.      by MultiFinder. Once we determine that an event is an osEvent, we look at the
  98.      high byte of the message sent to determine which kind it is. To differentiate
  99.      suspend and resume events we check the resumeMask bit.}
  100.     kOSEvent                = app4Evt;    {event used by MultiFinder}
  101.     kSuspendResumeMessage    = 1;        {high byte of suspend/resume event message}
  102.     kResumeMask                = 1;        {bit of message field for resume vs. suspend}
  103.     kNoEvents                = 0;        {no events mask}
  104.  
  105.     {1.01 - kMinHeap - This is the minimum result from the following
  106.      equation:
  107.             
  108.             ORD(GetApplLimit) - ORD(ApplicationZone)
  109.             
  110.      for the application to run. It will insure that enough memory will
  111.      be around for reasonable-sized scraps, FKEYs, etc. to exist with the
  112.      application, and still give the application some 'breathing room'.
  113.      To derive this number, we ran under a MultiFinder partition that was
  114.      our requested minimum size, as given in the 'SIZE' resource.}
  115.      
  116.     kMinHeap    = 21 * 1024;
  117.     
  118.     {1.01 - kMinSpace - This is the minimum result from PurgeSpace, when called
  119.      at initialization time, for the application to run. This number acts
  120.      as a double-check to insure that there really is enough memory for the
  121.      application to run, including what has been taken up already by
  122.      pre-loaded resources, the scrap, code, and other sundry memory blocks.}
  123.      
  124.     kMinSpace    = 8 * 1024;
  125.     
  126.     {kExtremeNeg and kExtremePos are used to set up wide open rectangles and regions.}
  127.     kExtremeNeg    = -32768;
  128.     kExtremePos    = 32767 - 1;            {required for old region bug}
  129.     
  130.     {The following constants are all resource IDs, corresponding to resources in Sample.r.}
  131.     rMenuBar    = 128;                    {application's menu bar}
  132.     rAboutAlert    = 128;                    {about alert}
  133.     rUserAlert    = 129;                    {error user alert}
  134.     rWindow        = 128;                    {application's window}
  135.     rStopRect    = 128;                    {rectangle for Stop light}
  136.     rGoRect        = 129;                    {rectangle for Go light}
  137.  
  138.     {The following constants are used to identify menus and their items. The menu IDs
  139.      have an "m" prefix and the item numbers within each menu have an "i" prefix.}
  140.     mApple        = 128;                    {Apple menu}
  141.     iAbout        = 1;
  142.  
  143.     mFile        = 129;                    {File menu}
  144.     iNew        = 1;
  145.     iClose        = 4;
  146.     iQuit        = 12;
  147.  
  148.     mEdit        = 130;                    {Edit menu}
  149.     iUndo        = 1;
  150.     iCut        = 3;
  151.     iCopy        = 4;
  152.     iPaste        = 5;
  153.     iClear        = 6;
  154.  
  155.     mLight        = 131;                    {Light menu}
  156.     iStop        = 1;
  157.     iGo            = 2;
  158.     
  159.     {1.01 - kDITop and kDILeft are used to locate the Disk Initialization dialogs.}
  160.     kDITop        = $0050;
  161.     kDILeft        = $0070;
  162.  
  163.  
  164. VAR
  165.     {The "g" prefix is used to emphasize that a variable is global.}
  166.  
  167.     {GMac is used to hold the result of a SysEnvirons call. This makes
  168.      it convenient for any routine to check the environment. It is
  169.      global information, anyway.}
  170.     gMac                : SysEnvRec;    {set up by Initialize}
  171.  
  172.     {GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  173.      trap is available. If it is false, we know that we must call GetNextEvent.}
  174.     gHasWaitNextEvent    : BOOLEAN;        {set up by Initialize}
  175.  
  176.     {GInBackground is maintained by our osEvent handling routines. Any part of
  177.      the program can check it to find out if it is currently in the background.}
  178.     gInBackground        : BOOLEAN;        {maintained by Initialize and DoEvent}
  179.  
  180.  
  181.     {The following globals are the state of the window. If we supported more than
  182.      one window, they would be attatched to each document, rather than globals.}
  183.  
  184.     {GStopped tells whether the stop light is currently on stop or go.}
  185.     gStopped            : BOOLEAN;        {maintained by Initialize and SetLight}
  186.  
  187.     {GStopRect and gGoRect are the rectangles of the two stop lights in the window.}
  188.     gStopRect            : Rect;            {set up by Initialize}
  189.     gGoRect                : Rect;            {set up by Initialize}
  190.  
  191.  
  192. {$S Initialize}
  193. FUNCTION TrapAvailable(tNumber: INTEGER; tType: TrapType): BOOLEAN;
  194.  
  195. {Check to see if a given trap is implemented. This is only used by the
  196.  Initialize routine in this program, so we put it in the Initialize segment.
  197.  The recommended approach to see if a trap is implemented is to see if
  198.  the address of the trap routine is the same as the address of the
  199.  Unimplemented trap.}
  200. {1.02 - Needs to be called after call to SysEnvirons so that it can check
  201.  if a ToolTrap is out of range of a pre-MacII ROM.}
  202.  
  203. BEGIN
  204.     IF (tType = ToolTrap) &
  205.         (gMac.machineType > envMachUnknown) &
  206.         (gMac.machineType < envMacII) THEN BEGIN        {it's a 512KE, Plus, or SE}
  207.         tNumber := BAND(tNumber, $03FF);
  208.         IF tNumber > $01FF THEN                            {which means the tool traps}
  209.             tNumber := _Unimplemented;                    {only go to $01FF}
  210.     END;
  211.     TrapAvailable := NGetTrapAddress(tNumber, tType) <>
  212.                         NGetTrapAddress(_Unimplemented, ToolTrap);
  213. END; {TrapAvailable}
  214.  
  215.  
  216. {$S Main}
  217. FUNCTION IsDAWindow(window: WindowPtr): BOOLEAN;
  218.  
  219. {Check if a window belongs to a desk accessory.}
  220.  
  221. BEGIN
  222.     IF window = NIL THEN
  223.         IsDAWindow := FALSE
  224.     ELSE    {DA windows have negative windowKinds}
  225.         IsDAWindow := (WindowPeek(window)^.windowKind < 0);
  226. END; {IsDAWindow}
  227.  
  228.  
  229. {$S Main}
  230. FUNCTION IsAppWindow(window: WindowPtr): BOOLEAN;
  231.  
  232. {Check to see if a window belongs to the application. If the window pointer
  233.  passed was NIL, then it could not be an application window. WindowKinds
  234.  that are negative belong to the system and windowKinds less than userKind
  235.  are reserved by Apple except for windowKinds equal to dialogKind, which
  236.  mean it is a dialog.
  237.  1.02 - In order to reduce the chance of accidentally treating some window
  238.  as an AppWindow that shouldn't be, we'll only return true if the windowkind
  239.  is userKind. If you add different kinds of windows to Sample you'll need
  240.  to change how this all works.}
  241.  
  242. BEGIN
  243.     IF window = NIL THEN
  244.         IsAppWindow := FALSE
  245.     ELSE    {application windows have windowKinds = userKind (8)}
  246.         WITH WindowPeek(window)^ DO
  247.             IsAppWindow := (windowKind = userKind);
  248. END; {IsAppWindow}
  249.  
  250.  
  251. {$S Main}
  252. PROCEDURE AlertUser;
  253.  
  254. {Display an alert that tells the user an error occurred, then exit the program.
  255.  This routine is used as an ultimate bail-out for serious errors that prohibit
  256.  the continuation of the application. Errors that do not require the termination
  257.  of the application should be handled in a different manner. Error checking and
  258.  reporting has a place even in the simplest application. For simplicity, the alert
  259.  displayed here only says that an error occurred, but not what it was. There are
  260.  various methods available for being more specific.}
  261.  
  262. VAR
  263.     itemHit    : INTEGER;
  264. BEGIN
  265.     SetCursor(qd.arrow);
  266.     itemHit := Alert(rUserAlert, NIL);
  267.     ExitToShell;
  268. END; {AlertUser}
  269.  
  270.  
  271. {$S Main}
  272. FUNCTION DoCloseWindow(window: WindowPtr) : BOOLEAN;
  273.  
  274. {Close a window.}
  275.  
  276. {1.01 - At this point, if there was a document associated with a
  277.  window, you could do any document saving processing if it is 'dirty'.
  278.  DoCloseWindow would return TRUE if the window actually closes, i.e.,
  279.  the user does not cancel from a save dialog. This result is handy when
  280.  the user quits an application, but then cancels a save of a document
  281.  associated with a window. We also added code to close the application
  282.  window since otherwise, the termination routines would never stop looping,
  283.  waiting for FrontWindow to return NIL.}
  284.  
  285. BEGIN
  286.     DoCloseWindow := TRUE;
  287.     IF IsDAWindow(window) THEN
  288.         CloseDeskAcc(WindowPeek(window)^.windowKind)
  289.     ELSE IF IsAppWindow(window) THEN
  290.         CloseWindow(window);
  291. END; {DoCloseWindow}
  292.  
  293.  
  294. {$S Initialize}
  295. FUNCTION GoGetRect(rectID: INTEGER; VAR theRect: Rect) : BOOLEAN;
  296.  
  297. {This utility loads the global rectangles that are used by the window
  298.  drawing routines. It shows how the resource manager can be used to hold
  299.  values in a convenient manner. These values are then easily altered without
  300.  having to re-compile the source code. In this particular case, we know
  301.  that this routine is being called at initialization time. Therefore,
  302.  if this returns FALSE, we will assume that the application is in such
  303.  bad shape that we should just exit. Your error handling may differ, but
  304.  the check should still be made.}
  305.  
  306. {1.01 - Changed GoGetRect to return a BOOLEAN that indicates if it was successful
  307.  in getting the rectangle rather than just doing ExitToShell.}
  308.  
  309. TYPE
  310.     RectPtr        = ^Rect;
  311.     RectHnd        = ^RectPtr;
  312. VAR
  313.     resource    : Handle;
  314. BEGIN
  315.     resource := GetResource('RECT', rectID);
  316.     IF resource <> NIL THEN BEGIN
  317.         GoGetRect := TRUE;
  318.         theRect := RectHnd(resource)^^;
  319.         END
  320.     ELSE
  321.         GoGetRect := FALSE;
  322. END; {GoGetRect}
  323.  
  324.  
  325. {$S Initialize}
  326. PROCEDURE Initialize;
  327.  
  328. {Set up the whole world, including global variables, Toolbox managers,
  329.  and menus. We also create our one application window at this time.
  330.  Since window storage is non-relocateable, how and when to allocate space
  331.  for windows is very important so that heap fragmentation does not occur.
  332.  Because Sample has only one window and it is only disposed when the application
  333.  quits, we will allocate its space here, before anything that might be a locked
  334.  relocatable object gets into the heap. This way, we can force its storage to be
  335.  in the lowest memory available in the heap. Window storage can differ widely
  336.  amongst applications depending on how many windows are created and disposed.
  337.  If a failure occurs here, we will consider that the application is in such
  338.  bad shape that we should just exit. Your error handling may differ, but
  339.  the checks should still be made.}
  340.  
  341. {1.01 - The code that used to be part of ForceEnvirons has been moved into
  342.  this module. If an error is detected, instead of merely doing an ExitToShell,
  343.  which leaves the user without much to go on, we call AlertUser, which puts
  344.  up a simple alert that just says an error occurred and then calls ExitToShell.
  345.  In the interests of keeping things simple, the alert does not state the specific
  346.  cause of the error, but a more informative alert would be appropriate for more
  347.  sophisticated applications. Since there is no other cleanup needed at this point
  348.  if an error is detected, this form of error- handling is acceptable. If more
  349.  sophisticated error recovery is needed, a signal mechanism, such as is provided
  350.  by Signals, can be used.}
  351.  
  352. VAR
  353.     menuBar            : Handle;
  354.     window            : WindowPtr;
  355.     ignoreError        : OSErr;
  356.     total, contig    : LongInt;
  357.     ignoreResult    : BOOLEAN;
  358.     event            : EventRecord;
  359.     count            : INTEGER;
  360.  
  361. BEGIN
  362.     gInBackground := FALSE;
  363.  
  364.     InitGraf(@qd.thePort);
  365.     InitFonts;
  366.     InitWindows;
  367.     InitMenus;
  368.     TEInit;
  369.     InitDialogs(NIL);
  370.     InitCursor;
  371.     
  372.     {Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  373.      if you are using it.}
  374.     {NOTE -- It is no longer necessary, and actually unhealthy, to check
  375.      PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  376.      of checking for port availability themselves.}
  377.     
  378.     {This next bit of code is necessary to allow the default button of our
  379.      alert be outlined.
  380.      1.02 - Changed to call EventAvail so that we don't lose some important
  381.      events.}
  382.      
  383.     FOR count := 1 TO 3 DO
  384.         ignoreResult := EventAvail(everyEvent, event);
  385.     
  386.     {Ignore the error returned from SysEnvirons; even if an error occurred,
  387.      the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  388.      call to SysEnvirons by calling it after initializing AppleTalk.}
  389.      
  390.     ignoreError := SysEnvirons(kSysEnvironsVersion, gMac);
  391.     
  392.     {Make sure that the machine has at least 128K ROMs. If it doesn't, exit.}
  393.     
  394.     IF gMac.machineType < 0 THEN AlertUser;
  395.     
  396.     {1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  397.      in TrapAvailable if a tool trap value is out of range.}
  398.      
  399.     gHasWaitNextEvent := TrapAvailable(_WaitNextEvent, ToolTrap);
  400.  
  401.     {1.01 - We used to make a check for memory at this point by examining ApplLimit,
  402.      ApplicationZone, and StackSpace and comparing that to the minimum size we told
  403.      MultiFinder we needed. This did not work well because it assumed too much about
  404.      the relationship between what we asked MultiFinder for and what we would actually
  405.      get back, as well as how to measure it. Instead, we will use an alternate
  406.      method comprised of two steps.}
  407.      
  408.     {It is better to first check the size of the application heap against a value
  409.      that you have determined is the smallest heap the application can reasonably
  410.      work in. This number should be derived by examining the size of the heap that
  411.      is actually provided by MultiFinder when the minimum size requested is used.
  412.      The derivation of the minimum size requested from MultiFinder is described
  413.      in Sample.h. The check should be made because the preferred size can end up
  414.      being set smaller than the minimum size by the user. This extra check acts to
  415.      insure that your application is starting from a solid memory foundation.}
  416.      
  417.     IF ORD(GetApplLimit) - ORD(ApplicationZone) < kMinHeap THEN AlertUser;
  418.     
  419.     {Next, make sure that enough memory is free for your application to run. It
  420.      is possible for a situation to arise where the heap may have been of required
  421.      size, but a large scrap was loaded which left too little memory. To check for
  422.      this, call PurgeSpace and compare the result with a value that you have determined
  423.      is the minimum amount of free memory your application needs at initialization.
  424.      This number can be derived several different ways. One way that is fairly
  425.      straightforward is to run the application in the minimum size configuration
  426.      as described previously. Call PurgeSpace at initialization and examine the value
  427.      returned. However, you should make sure that this result is not being modified
  428.      by the scrap's presence. You can do that by calling ZeroScrap before calling
  429.      PurgeSpace. Make sure to remove that call before shipping, though.}
  430.      
  431.     PurgeSpace(total, contig);
  432.     IF total < kMinSpace THEN AlertUser;
  433.  
  434.     {The extra benefit to waitng until after the Toolbox Managers have been initialized
  435.      before checking memory is that we can now give the user an alert to tell him what
  436.      happened. Although it is possible that the memory situation could be worsened by
  437.      displaying an alert, MultiFinder would gracefully exit the application with
  438.      an informative alert if memory became critical. Here we are acting more
  439.      in a preventative manner to avoid future disaster from low-memory problems.}
  440.      
  441.     {We will allocate our own window storage instead of letting the Window
  442.      Manager for two reasons. One, GetNewWindow locks the 'WIND' resource
  443.      handle before calling NewWindow and this can lead to heap fragmentation.
  444.      Two, it takes just as much time for NewWindow to get the memory as it
  445.      does for us to get it.}
  446.  
  447.     window := WindowPtr(NewPtr(SIZEOF(WindowRecord)));
  448.     IF window = NIL THEN AlertUser;
  449.     window := GetNewWindow(rWindow, Ptr(window), WindowPtr(-1));
  450.  
  451.     menuBar := GetNewMBar(rMenuBar);        {read menus into menu bar}
  452.     IF menuBar = NIL THEN AlertUser;
  453.     SetMenuBar(menuBar);                    {install menus}
  454.     DisposeHandle(menuBar);
  455.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    {add DA names to Apple menu}
  456.     DrawMenuBar;
  457.  
  458.     gStopped := TRUE;
  459.     IF NOT GoGetRect(rStopRect, gStopRect) THEN
  460.         AlertUser;                            {the stop light rectangle}
  461.     IF NOT GoGetRect(rGoRect, gGoRect) THEN
  462.         AlertUser;                            {the go light rectangle}
  463. END; {Initialize}
  464.  
  465.  
  466. (**************************************************************************************
  467. 1.01 - PROCEDURE DoCloseBehind(window: WindowPtr); was removed.
  468.  
  469. {1.01 - DoCloseBehind was a good idea for closing windows when quitting
  470.  and not having to worry about updating the windows, but it suffered
  471.  from a fatal flaw. If a desk accessory owned two windows, it would
  472.  close both those windows when CloseDeskAcc was called. When DoCloseBehind
  473.  got around to calling DoCloseWindow for that other window that was already
  474.  closed, things would go very poorly. Another option would be to have a
  475.  procedure, GetRearWindow, that would go through the window list and return
  476.  the last window. Instead, we decided to present the standard approach
  477.  of getting and closing FrontWindow until FrontWindow returns NIL. This
  478.  has a potential benefit in that the window whose document needs to be saved
  479.  may be visible since it is the front window, therefore decreasing the
  480.  chance of user confusion. For aesthetic reasons, the windows in the
  481.  application should be checked for updates periodically and have the
  482.  updates serviced.}
  483. **************************************************************************************)
  484.  
  485.  
  486. {$S Main}
  487. PROCEDURE Terminate;
  488.  
  489. {Clean up the application and exits. We close all of the windows so that
  490.  they can update their documents, if any.}
  491.  
  492. {1.01 - If we find out that a cancel has occurred, we won't exit to the
  493.  shell, but will return instead.}
  494.  
  495. VAR
  496.     aWindow    : WindowPtr;
  497.     closed    : BOOLEAN;
  498.  
  499. BEGIN
  500.     closed := TRUE;
  501.     REPEAT
  502.         aWindow := FrontWindow;                    {get the current front window}
  503.         IF aWindow <> NIL THEN
  504.             closed := DoCloseWindow(aWindow);    {close this window}
  505.     UNTIL (NOT closed) | (aWindow = NIL);        {do all windows}
  506.     IF closed THEN
  507.         ExitToShell;                            {exit if no cancellation}
  508. END; {Terminate}
  509.  
  510.  
  511. {$S Main}
  512. PROCEDURE SetLight(window: WindowPtr; newStopped: BOOLEAN);
  513.  
  514. {Change the setting of the light.}
  515.  
  516. BEGIN
  517.     IF newStopped <> gStopped THEN BEGIN
  518.         gStopped := newStopped;
  519.         SetPort(window);
  520.         InvalRect(window^.portRect);
  521.     END;
  522. END; {SetLight}
  523.  
  524.  
  525. {$S Main}
  526. PROCEDURE AdjustMenus;
  527.  
  528. {Enable and disable menus based on the current state.
  529.  The user can only select enabled menu items. We set up all the menu items
  530.  before calling MenuSelect or MenuKey, since these are the only times that
  531.  a menu item can be selected. Note that MenuSelect is also the only time
  532.  the user will see menu items. This approach to deciding what enable/
  533.  disable state a menu item has the advantage of concentrating all the decision-
  534.  making in one routine, as opposed to being spread throughout the application.
  535.  Other application designs may take a different approach that may or may not be
  536.  just as valid.}
  537.  
  538. VAR
  539.     window            : WindowPtr;
  540.     menu            : MenuHandle;
  541.  
  542. BEGIN
  543.     window := FrontWindow;
  544.  
  545.     menu := GetMenuHandle(mFile);
  546.     IF IsDAWindow(window) THEN                {we can allow desk accessories to be closed from the menu}
  547.         EnableItem(menu, iClose)
  548.     ELSE
  549.         DisableItem(menu, iClose);            {but not our traffic light window}
  550.  
  551.     menu := GetMenuHandle(mEdit);
  552.     IF IsDAWindow(window) THEN BEGIN        {a desk accessory might need the edit menu}
  553.         EnableItem(menu, iUndo);
  554.         EnableItem(menu, iCut);
  555.         EnableItem(menu, iCopy);
  556.         EnableItem(menu, iPaste);
  557.         EnableItem(menu, iClear);
  558.     END ELSE BEGIN                            {but we know we do not}
  559.         DisableItem(menu, iUndo);
  560.         DisableItem(menu, iCut);
  561.         DisableItem(menu, iCopy);
  562.         DisableItem(menu, iClear);
  563.         DisableItem(menu, iPaste);
  564.     END;
  565.  
  566.     menu := GetMenuHandle(mLight);
  567.     IF IsAppWindow(window) THEN BEGIN        {we know that it must be the traffic light}
  568.         EnableItem(menu, iStop);
  569.         EnableItem(menu, iGo);
  570.     END ELSE BEGIN
  571.         DisableItem(menu, iStop);
  572.         DisableItem(menu, iGo);
  573.     END;
  574.     CheckItem(menu, iStop, gStopped);        {we can also determine check/uncheck state, too}
  575.     CheckItem(menu, iGo, NOT gStopped);
  576. END; {AdjustMenus}
  577.  
  578.  
  579. {$S Main}
  580. PROCEDURE DoMenuCommand(menuResult: LONGINT);
  581.  
  582. {This is called when an item is chosen from the menu bar (after calling
  583.  MenuSelect or MenuKey). It performs the right operation for each command.
  584.  It is good to have both the result of MenuSelect and MenuKey go to
  585.  one routine like this to keep everything organized.}
  586.  
  587. VAR
  588.     menuID            : INTEGER;        {the resource ID of the selected menu}
  589.     menuItem        : INTEGER;        {the item number of the selected menu}
  590.     itemHit            : INTEGER;
  591.     daName            : Str255;
  592.     daRefNum        : INTEGER;
  593.     handledByDA        : BOOLEAN;
  594.     ignore            : BOOLEAN;
  595.  
  596. BEGIN
  597.     menuID := HiWord(menuResult);    {use built-ins (for efficiency)...}
  598.     menuItem := LoWord(menuResult);    {to get menu item number and menu number}
  599.     CASE menuID OF
  600.         mApple:
  601.             CASE menuItem OF
  602.                 iAbout:                {bring up alert for About}
  603.                     itemHit := Alert(rAboutAlert, NIL);
  604.                 OTHERWISE BEGIN        {all non-About items in this menu are DAs}
  605.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  606.                     daRefNum := OpenDeskAcc(daName);
  607.                 END;
  608.             END;
  609.         mFile:
  610.             CASE menuItem OF
  611.                 iClose:
  612.                     ignore := DoCloseWindow(FrontWindow); {we don't care if cancelled}
  613.                 iQuit:
  614.                     Terminate;
  615.             END;
  616.         mEdit:                        {call SystemEdit for DA editing & MultiFinder}
  617.             handledByDA := SystemEdit(menuItem-1);    {since we don't do any editing}
  618.         mLight:
  619.             CASE menuItem OF
  620.                 iStop:
  621.                     SetLight(FrontWindow, TRUE);
  622.                 iGo:
  623.                     SetLight(FrontWindow, FALSE);
  624.             END;
  625.     END;
  626.     HiliteMenu(0);                    {unhighlight what MenuSelect (or MenuKey) hilited}
  627. END; {DoMenuCommand}
  628.  
  629.  
  630. {$S Main}
  631. PROCEDURE DrawWindow(window: WindowPtr);
  632.  
  633. {Draw the contents of the application window. We do some drawing in color, using
  634.  Classic QuickDraw's color capabilities. This will be black and white on old
  635.  machines, but color on color machines. At this point, the window's visRgn is
  636.  set to allow drawing only where it needs to be done.}
  637.  
  638. BEGIN
  639.     SetPort(window);
  640.  
  641.     EraseRect(window^.portRect);    {clear out any garbage that might be left behind}
  642.     IF gStopped THEN                {draw a red (or white) stop light}
  643.         ForeColor(redColor)
  644.     ELSE
  645.         ForeColor(whiteColor);
  646.     PaintOval(gStopRect);
  647.     ForeColor(blackColor);
  648.     FrameOval(gStopRect);
  649.     IF NOT gStopped THEN            {draw a green (or white) go light}
  650.         ForeColor(greenColor)
  651.     ELSE
  652.         ForeColor(whiteColor);
  653.     PaintOval(gGoRect);
  654.     ForeColor(blackColor);
  655.     FrameOval(gGoRect);
  656. END; {DrawWindow}
  657.  
  658.  
  659. {$S Main}
  660. PROCEDURE DoContentClick(window: WindowPtr; event: EventRecord);
  661.  
  662. {This is called when a mouse-down event occurs in the content of a window.
  663.  Other applications might want to call FindControl, TEClick, etc., to
  664.  further process the click.}
  665.  
  666. BEGIN
  667.     SetLight(window, NOT gStopped);
  668. END; {DoContentClick}
  669.  
  670.  
  671. {$S Main}
  672. PROCEDURE DoUpdate(window: WindowPtr);
  673.  
  674. {This is called when an update event is received for a window.
  675.  It calls DrawWindow to draw the contents of an application window.
  676.  As an effeciency measure that does not have to be followed, it
  677.  calls the drawing routine only if the visRgn is non-empty. This
  678.  will handle situations where calculations for drawing or drawing
  679.  itself is very time-consuming.}
  680.  
  681. BEGIN
  682.     IF IsAppWindow(window) THEN BEGIN
  683.         BeginUpdate(window);                    {sets up the visRgn, clears updateRgn}
  684.         IF NOT EmptyRgn(window^.visRgn) THEN    {draw if updating needs to be done}
  685.             DrawWindow(window);
  686.         EndUpdate(window);                        {restores the visRgn}
  687.     END;
  688. END; {DoUpdate}
  689.  
  690.  
  691. {$S Main}
  692. PROCEDURE DoActivate(window: WindowPtr; becomingActive: BOOLEAN);
  693.  
  694. {This is called when a window is activated or deactivated.
  695.  In Sample, the Window Manager's handling of activate and
  696.  deactivate events is sufficient. Other applications may have
  697.  TextEdit records, controls, lists, etc., to activate/deactivate.}
  698.  
  699. BEGIN
  700.     IF IsAppWindow(window) THEN
  701.         IF becomingActive THEN
  702.             {do whatever you need to at activation}
  703.         ELSE
  704.             {do whatever you need to at deactivation};
  705. END; {DoActivate}
  706.  
  707.  
  708. {$S Main}
  709. PROCEDURE GetGlobalMouse(VAR mouse: Point);
  710.  
  711. {Get the global coordinates of the mouse. When you call OSEventAvail
  712.  it will return either a pending event or a null event. In either case,
  713.  the where field of the event record will contain the current position
  714.  of the mouse in global coordinates and the modifiers field will reflect
  715.  the current state of the modifiers. Another way to get the global
  716.  coordinates is to call GetMouse and LocalToGlobal, but that requires
  717.  being sure that thePort is set to a valid port.}
  718.  
  719. VAR
  720.     event    : EventRecord;
  721.     
  722. BEGIN
  723.     IF OSEventAvail(kNoEvents, event) THEN;    {we aren't interested in any events}
  724.     mouse := event.where;                    {just the mouse position}
  725. END;
  726.  
  727.  
  728. {$S Main}
  729. PROCEDURE AdjustCursor(mouse: Point; region: RgnHandle);
  730.  
  731. {Change the cursor's shape, depending on its position. This also calculates the region
  732.  where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  733.  that region, an event is generated, causing this routine to be called. This
  734.  allows us to change the region to the region the mouse is currently in. If
  735.  there is more to the event than just “the mouse moved”, we get called before the
  736.  event is processed to make sure the cursor is the right one. In any (ahem) event,
  737.  this is called again before we fall back into WNE.}
  738.  
  739.  
  740. VAR
  741.     window                : WindowPtr;
  742.     arrowRgn            : RgnHandle;
  743.     plusRgn                : RgnHandle;
  744.     globalPortRect        : Rect;
  745.     
  746.  
  747. BEGIN
  748.     window := FrontWindow;    {we only adjust the cursor when we are in front}
  749.     IF (NOT gInBackground) AND (NOT IsDAWindow(window)) THEN BEGIN
  750.         {calculate regions for different cursor shapes}
  751.         arrowRgn := NewRgn;
  752.         plusRgn := NewRgn;
  753.  
  754.         {start with a big, big rectangular region}
  755.         {1.01 - changed to kExtremeNeg and kExtremePos for consistency}
  756.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg,
  757.                             kExtremePos, kExtremePos);
  758.  
  759.         {calculate plusRgn}
  760.         IF IsAppWindow(window) THEN BEGIN
  761.             SetPort(window);            {make a global version of the portRect}
  762.             SetOrigin(-window^.portBits.bounds.left, -window^.portBits.bounds.top);
  763.             globalPortRect := window^.portRect;
  764.             RectRgn(plusRgn, globalPortRect);
  765.             SectRgn(plusRgn, window^.visRgn, plusRgn);
  766.             SetOrigin(0, 0);
  767.         END;
  768.  
  769.         {subtract other regions from arrowRgn}
  770.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  771.  
  772.         {change the cursor and the region parameter}
  773.         IF PtInRgn(mouse, plusRgn) THEN BEGIN
  774.             SetCursor(GetCursor(plusCursor)^^);
  775.             CopyRgn(plusRgn, region);
  776.         END ELSE BEGIN
  777.             SetCursor(qd.arrow);
  778.             CopyRgn(arrowRgn, region);
  779.         END;
  780.  
  781.         {get rid of our local regions}
  782.         DisposeRgn(arrowRgn);
  783.         DisposeRgn(plusRgn);
  784.     END;
  785. END; {AdjustCursor}
  786.  
  787.  
  788. {$S Main}
  789. PROCEDURE DoEvent(event: EventRecord);
  790.  
  791. {Do the right thing for an event. Determine what kind of event it is, and call
  792.  the appropriate routines.}
  793.  
  794. VAR
  795.     part, err    : INTEGER;
  796.     window        : WindowPtr;
  797.     hit            : BOOLEAN;
  798.     key            : CHAR;
  799.     aPoint        : Point;
  800.  
  801. BEGIN
  802.     CASE event.what OF
  803.         mouseDown: BEGIN
  804.             part := FindWindow(event.where, window);
  805.             CASE part OF
  806.                 inMenuBar: BEGIN            {process the menu command}
  807.                     AdjustMenus;
  808.                     DoMenuCommand(MenuSelect(event.where));
  809.                 END;
  810.                 inSysWindow:                {let the system handle the mouseDown}
  811.                     SystemClick(event, window);
  812.                 inContent:
  813.                     IF window <> FrontWindow THEN BEGIN
  814.                         SelectWindow(window);
  815.                         {DoEvent(event);}    {use this line for "do first click"}
  816.                     END ELSE
  817.                         DoContentClick(window, event);
  818.                 inDrag:                        {pass screenBits.bounds to get all gDevices}
  819.                     DragWindow(window, event.where, qd.screenBits.bounds);
  820.                 inGrow:;
  821.                 inZoomIn, inZoomOut:;
  822.             END;
  823.         END;
  824.         keyDown, autoKey: BEGIN                {check for menukey equivalents}
  825.             key := CHR(BAnd(event.message, charCodeMask));
  826.             IF BAnd(event.modifiers, cmdKey) <> 0 THEN    {Command key down}
  827.                 IF event.what = keyDown THEN BEGIN
  828.                     AdjustMenus;            {enable/disable/check menu items properly}
  829.                     DoMenuCommand(MenuKey(key));
  830.                 END;
  831.         END;                                {call DoActivate with the window and...}
  832.         activateEvt:                        {TRUE for activate, FALSE for deactivate}
  833.             DoActivate(WindowPtr(event.message), BAnd(event.modifiers, activeFlag) <> 0);
  834.         updateEvt:                          {call DoUpdate with the window to update}
  835.             DoUpdate(WindowPtr(event.message));
  836.         {1.01 - It is not a bad idea to at least call DIBadMount in response
  837.          to a diskEvt, so that the user can format a floppy.}
  838.         diskEvt:
  839.             IF HiWord(event.message) <> noErr THEN BEGIN
  840.                 SetPt(aPoint, kDILeft, kDITop);
  841.                 err := DIBadMount(aPoint, event.message);
  842.             END;
  843.         kOSEvent:
  844.             CASE BAnd(BRotL(event.message, 8), $FF) OF    {high byte of message}
  845.                 kSuspendResumeMessage: BEGIN
  846.                     gInBackground := BAnd(event.message, kResumeMask) = 0;
  847.                     DoActivate(FrontWindow, NOT gInBackground);
  848.                 END;
  849.             END;
  850.     END;
  851. END; {DoEvent}
  852.  
  853.  
  854. {$S Main}
  855. PROCEDURE EventLoop;
  856.  
  857. {Get events forever, and handle them by calling DoEvent.
  858.  Get the events by calling WaitNextEvent, if it's available, otherwise
  859.  by calling GetNextEvent. Also call AdjustCursor each time through the loop.}
  860.  
  861. VAR
  862.     cursorRgn    : RgnHandle;
  863.     gotEvent    : BOOLEAN;
  864.     event        : EventRecord;
  865.     mouse        : Point;
  866.  
  867. BEGIN
  868.     cursorRgn := NewRgn;                {we’ll pass WNE an empty region the 1st time thru}
  869.     REPEAT
  870.         IF gHasWaitNextEvent THEN BEGIN    {put us 'asleep' forever under MultiFinder}
  871.             GetGlobalMouse(mouse);        {since we might go to sleep}
  872.             AdjustCursor(mouse, cursorRgn);
  873.             gotEvent := WaitNextEvent(everyEvent, event, MAXLONGINT, cursorRgn);
  874.         END ELSE BEGIN
  875.             SystemTask;                    {must be called if using GetNextEvent}
  876.             gotEvent := GetNextEvent(everyEvent, event);
  877.         END;
  878.         IF gotEvent THEN BEGIN
  879.             AdjustCursor(event.where, cursorRgn);    {make sure we have the right cursor}
  880.             DoEvent(event);
  881.         END;
  882.         {If you are using modeless dialogs that have editText items,
  883.          you will want to call IsDialogEvent to give the caret a chance
  884.          to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  885.          for a non-NIL value before calling IsDialogEvent.}
  886.     UNTIL FALSE;                        {loop forever; we quit through an ExitToShell}
  887. END; {EventLoop}
  888.  
  889.  
  890. PROCEDURE _DataInit; EXTERNAL;
  891.  
  892. {This routine is part of the MPW runtime library. This external
  893.  reference to it is done so that we can unload its segment, %A5Init.}
  894.  
  895. {$S Main}
  896. BEGIN
  897.     UnloadSeg(@_DataInit);    {note that _DataInit must not be in Main!}
  898.     
  899.     {1.01 - call to ForceEnvirons removed}
  900.     {If you have stack requirements that differ from the default,
  901.      then you could use SetApplLimit to increase StackSpace at 
  902.      this point, before calling MaxApplZone.}
  903.      
  904.     MaxApplZone;            {expand the heap so code segments load at the top}
  905.  
  906.     Initialize;                {initialize the program}
  907.     UnloadSeg(@Initialize);    {note that Initialize must not be in Main!}
  908.  
  909.     EventLoop;                {call the main event loop}
  910. END.
  911.